const fs = require('fs');
const md5 = require('md5');
const axios = require('axios')
// 读取JSON文件
fs.readFile('./src/assets/zh.json', 'utf8', (err, data) => {
    if (err) {
        console.error("Error reading JSON file:", err);
        return;
    }

    // 解析JSON数据
    let jsonData;
    try {
        jsonData = JSON.parse(data);
    } catch (parseErr) {
        console.error("Error parsing JSON:", parseErr);
        return;
    }
    // 翻译JSON中的值为英文
    const translatedJSON = {};
    const jsonKeys = Object.keys(jsonData)
    let i = 0
    loopTransform(jsonData,translatedJSON,jsonKeys,0)
});

function loopTransform(curJson,tarJson,keys,index){
    const q = curJson[keys[index]]
    const from = 'zh'
    const to = 'en'
    const appid = '20231220001916782'
    const secretKey = 'khOqYRxAeGg15SXORIyo'
    let salt = new Date().getTime()
    let sign = md5(appid + q + salt + secretKey)
    let url = `https://fanyi-api.baidu.com/api/trans/vip/translate?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`
    axios.get(url).then(res=>{
        let dst = res.data.trans_result[0].dst
        tarJson[keys[index]] = dst.charAt(0).toUpperCase() + dst.slice(1);
        setTimeout(()=>{
            index++
            if (index < keys.length){
                loopTransform(curJson,tarJson,keys,index)
            } else {
                fs.writeFile('./src/assets/en.json', JSON.stringify(tarJson), 'utf8', (err) => {
                    if (err) {
                        console.error('写入文件时发生错误：', err);
                        return;
                    }
                    console.log('数据已成功写入到 en.json 文件中。');
                });
            }
        },100)
    })
}